package org.jside.cdn;

import java.util.Arrays;

import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.xidea.lite.parser.ParseChain;
import org.xidea.lite.parser.ParseContext;
import org.xidea.lite.parser.NodeParser;
import org.xidea.lite.parser.impl.AbstractHTMLNodeParser;

public class CDNOptimizeParser extends AbstractHTMLNodeParser implements
		NodeParser<Element> {
	public static final String STATUS_KEY = CDNOptimizeParser.class.getName();

	@Override
	public void parseHTMLElement(Element node, ParseContext context,
			ParseChain chain) {
		ScriptContext sc = (ScriptContext) context.getAttribute(STATUS_KEY);
		if (sc == null) {
			sc = new ScriptContext(context);
			context.setAttribute(STATUS_KEY, sc);
		}
		if (node.getTagName().equals("script")) {
			if (node.hasAttribute("src")) {
				String src = node.getAttribute("src");
				String[] paths = getCDNPath(src);
				if (paths!= null) {
					for (String path : paths) {
						sc.addPath(path);
					}
					sc.setSrc(src);
					context.append("<script");
					NamedNodeMap attrs = node.getAttributes();
					for (int i = 0; i < attrs.getLength(); i++) {
						Attr attr = (Attr) attrs.item(i);
						if (!attr.getName().equals("src")) {
							context.parse(attr);
						}
					}
					context.append(" src=\"");
					context.appendAll(Arrays.asList((Object)sc));
					context.append("\"></script>");
					return;
				}
			} else {
				sc.addScript(node.getTextContent());
			}
		} else {
			NamedNodeMap attrs = node.getAttributes();
			for (int i = 0; i < attrs.getLength(); i++) {
				Attr attr = (Attr) attrs.item(i);
				if (attr.getName().startsWith("on")) {
					sc.addScript("function(event){"+attr.getValue()+"\n}");
				}
			}
		}
		chain.process(node);
	}

	public String[] getCDNPath(String src) {
		int p = src.indexOf("/=");;
		src = src.substring(p+2);
		return src.trim().split("[^\\w\\.\\$\\:\\*]+");
	}

}
